#include "Sphere.h"
#include <cmath>
#include <stdlib.h>
#include <stdio.h>

void Sphere::add(float r, Vector3<float> c){
    radius = r;
    center = c;
    material = new Material();

}
Vector3<float> Sphere::getNormal(Vector3<float> surfacePoint){
    float test1 = surfacePoint[0] - center[0];
    float test2 = surfacePoint[1] - center[1];
    float test3 = surfacePoint[2] - center[2];

    float* norm;
    float vals[3];
    vals[0] = test1;
    vals[1] = test2;
    vals[2] = test3;
    norm = vals;
    return Vector3<float>(test1, test2, test3).Normalize();


}

float Sphere::intersect(Ray &r){

    Vector3<float> p;
    p =  r.origin - this->center;

    float t, t0, t1;
    float a;
    float b;
    float c;

    a = r.direction * r.direction;
    b = 2.0 * (r.direction * p);
    c = (p * p) - (this->radius * this->radius);

    //Om inga positiva rötter finns träffar inte sfären
    if ((b * b) - (4.0 * a * c) < 0){
        return 0;
    }

    //Annars, hitta rötter
    else{
        float q = 0.0;
        if(b < 0){
            q = (-b + sqrt( (b*b) - (4.0*a*c) )) * 0.5;
        }
        else{
             q = (-b - sqrt( (b*b) - (4.0*a*c) )) * 0.5;
        }

        t0 = q / a;
        t1 = c / q;

    }

    if (t0 > t1){
        // if t0 is bigger than t1 swap them around
        float temp = t0;
        t0 = t1;
        t1 = temp;
    }

    // if t1 is less than zero, the object is in the ray's negative direction
    // and consequently the ray misses the sphere
    if (t1 < 0) return 0;

    // if t0 is less than zero, the intersection point is at t1
    if (t0 < 0){
        t = t1;
        return t;
    }

    // else the intersection point is at t0
    else{
        t = t0;
        return t;
    }
}





